package com.loanapp.server.sso.interceptor.login;

import com.alibaba.fastjson.JSON;
import com.loanapp.base.common.dto.ResponseDto;
import com.loanapp.base.common.utils.StringUtil;
import com.loanapp.base.controller.support.HttpKit;
import com.loanapp.server.sso.constant.LoginValidate;
import com.loanapp.server.user.api.user.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {

   @Autowired
   private RedisTemplate redisTemplate;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            return true;
        }

        final HandlerMethod handlerMethod = (HandlerMethod) handler;
        final Method method = handlerMethod.getMethod();
        final Class<?> clazz = method.getDeclaringClass();
        if (clazz.isAnnotationPresent(LoginValidate.class) || method.isAnnotationPresent(LoginValidate.class)) {
           String token= request.getHeader("Authorization");
           if(StringUtil.isEmpty(token)){
              HttpKit.responseJson(HttpKit.getResponse(),JSON.toJSONString(ResponseDto.build(111,"登录失效")));
              return false;
           }
           else {
               User user= (User) redisTemplate.opsForValue().get(token);
               if(user==null){
                   HttpKit.responseJson(HttpKit.getResponse(),JSON.toJSONString(ResponseDto.build(111,"登录失效")));
                   return false;
               }
           }
        }
        return true;
    }
}
